package com.yzt.config.security;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.session.InvalidSessionStrategy;

import com.alibaba.fastjson.JSON;
import com.yzt.base.kit.Base;
import com.yzt.base.utils.RequestUtil;

public class CustomInvalidSessionStrategy implements InvalidSessionStrategy {

	private final RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

	private boolean createNewSession = true;

	@Override
	public void onInvalidSessionDetected(HttpServletRequest request, HttpServletResponse response) throws IOException {
		boolean isAjax = RequestUtil.isAjax(request);
		if (isAjax) {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html;charset=UTF-8");
			response.setStatus(403);
			PrintWriter out = response.getWriter();
			out.print(JSON.toJSONString(Base.fail(403, "登录超时")));
		} else {
			if (createNewSession) {
				request.getSession();
			}
			this.redirectStrategy.sendRedirect(request, response, "/user_login");
		}

	}

	public void setCreateNewSession(boolean createNewSession) {
		this.createNewSession = createNewSession;
	}

}
